package controller;

import information.AbstractInformation;

import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import table.AbstractTable;

import models.TableSelectionModel;

public class InformationListener implements ListSelectionListener{

	private int lastRow = -1;
	
	private SelectedViewController viewController;
	private AbstractInformation previousInformation;

	public InformationListener(SelectedViewController viewController){
		this.viewController = viewController;
	}

	@Override
	public void valueChanged(ListSelectionEvent e) {
		TableSelectionModel selectionModel = (TableSelectionModel)e.getSource();
		
		int viewID = selectionModel.getTable().getTableID();
		int currentRow = selectionModel.getAnchorSelectionIndex();
		
		AbstractInformation information = viewController.getCurrentInformation();
		
		if (currentRow != lastRow && currentRow != -1 && information != null) {
			
			AbstractTable table = selectionModel.getTable();
			
			if (viewID == AbstractTable.VINYL_VIEW) {
				if (previousInformation != null)
					previousInformation.clear();
				previousInformation = information;
				
				Integer vinylID = (Integer) table.getValueAt(currentRow, 0);
				Integer storageID = (Integer) table.getValueAt(currentRow, 6);
	
				information.populate(vinylID, storageID);
			}
			
			if (viewID == AbstractTable.BORROWED_VIEW) {
				if (previousInformation != null)
					previousInformation.clear();
				previousInformation = information;
			
				Integer ownerID = (Integer) table.getValueAt(currentRow, 4);
				
				information.populate(ownerID, 0);
			}
			
			if (viewID == AbstractTable.RENTED_OUT_VIEW) {
				if (previousInformation != null)
					previousInformation.clear();
				previousInformation = information;
							
				Integer memberID = (Integer) table.getValueAt(currentRow, 5);
				
				information.populate(memberID, 0);
			}
			information.revalidate();	
		}
		lastRow = currentRow;
	}
	
	@Deprecated
	public void setLastRow(int lastRow) {
		this.lastRow = lastRow;
	}
	
	
}
